<template></template>
<script setup lang="ts">
import * as THREE from "three";
import json from "@/assets/810000-sc.json";
import { onMounted } from "vue";
import * as turf from "@turf/turf";
import { offsetXY } from "../utils/offsetXY";
import { useTresContext } from "@tresjs/core";
import { lableManager } from "../store/index";
const {
  camera,
  scene,
  sizes: { width, height },
} = useTresContext();
/**
 * 标签三维转屏幕坐标
 */
const Vector3ToScreenPosition = (x: number, y: number, z: number) => {
  /**
   * 立方体世界坐标转屏幕坐标
   */
  //获取网格模型boxMesh的世界坐标
  var worldVector = new THREE.Vector3(x, y, z);
  //世界坐标转标准设备坐标
  var standardVector = worldVector.project(camera.value!);
  var a = width.value / 2;
  var b = height.value / 2;
  var left = Math.round(standardVector.x * a + a); //标准设备坐标转屏幕坐标
  var top = Math.round(-standardVector.y * b + b); //标准设备坐标转屏幕坐标
  return { left, top };
};

const renderLable = (center: number[], name: string) => {
  /**
   * 纠偏
   */
  const [x, y] = offsetXY(center as [number, number])!;
  const update = () => {
    const { left, top } = Vector3ToScreenPosition(x, -y, 0);
    const result = lableManager.value.find((item) => item.name === name);
    if (result) {
      result.left = left;
      result.top = top;
    }
  };
  lableManager.value.push({
    name,
    left: x,
    top: y,
    update,
  });
  update();
};
const init = () => {
  for (let index = 0; index < json.features.length; index++) {
    const {
      geometry: { coordinates, type },
      properties: { name },
    } = json.features[index];
    if (type === "Polygon") {
      /**
       * 获取质心
       */
      let polygon = turf.polygon(coordinates);
      let center = turf.centerOfMass(polygon);
      renderLable(center.geometry.coordinates, name);
    }
    if (type === "MultiPolygon") {
      let multiPolygon = turf.multiPolygon(coordinates);
      let center = turf.centerOfMass(multiPolygon);
      renderLable(center.geometry.coordinates, name);
    }
  }
};

onMounted(() => {
  init();
});
</script>
